package com.hunttown.mes.common.qcloud.qcloudcos;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.InitializingBean;

/**
 * 获取客户端存储实例（单例）
 * 不适用于多用户
 * created by wangjunfu on 2020-06-13
 */
public class CosInstance implements InitializingBean {

    //客户端实例
    private static volatile COSClient cosClient;

    public void afterPropertiesSet() throws Exception {
        //启动时执行
        //init(CosConstants.SecretID, CosConstants.SecretKey, CosConstants.Region);
    }

    /**
     * 初始化
     *
     * @param secretId  腾讯云COS的secretId
     * @param secretKey 腾讯云COS的secretKey
     * @param region    腾讯云COS存储地区
     */
    private static void init(String secretId, String secretKey, String region) {
        //1.初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

        //2.设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        //clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region regionobj = new Region(region);
        ClientConfig clientConfig = new ClientConfig(regionobj);

        //3.生成 cos 客户端。
        cosClient = new COSClient(cred, clientConfig);
    }

    //获取客户端
    public static COSClient getInstance(String secretId, String secretKey, String region) {
        if (cosClient == null) {
            init(secretId, secretKey, region);
        }
        return cosClient;
    }

    //关闭客户端(关闭后台线程)
    public static void closeCosClient(COSClient cosClient) {
        if (cosClient != null) {
            cosClient.shutdown();
        }
    }
}
